﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.SalesOrder;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 销售出库
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrderSalesExWarehouseController : ControllerBase
    {
        public IOrderSalesExWarehouseServices Services { get; }
        public LogHelper LogHelper { get; }

        public OrderSalesExWarehouseController(IOrderSalesExWarehouseServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }


        /// <summary>
        /// 获取所有销售出库单数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();

            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";


                //写日志
                await LogHelper.WriteErrorLog("销售出库单-获取所有", ex, HttpContext);
            }
            return Ok(status);
        }



        /// <summary>
        /// 分页获取销售出库单数据
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="Number">出库单编号</param>
        /// <param name="Status">单据状态 -1：全部 0待审核 1已审核 2已退货</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] int Status=-1)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize, Number, Status);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, Status);

            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";

                //写日志
                await LogHelper.WriteErrorLog("销售出库-分页获取", ex, HttpContext);
            }
            return Ok(status);
        }


        /// <summary>
        /// 根据单据Id获取单据商品
        /// </summary>
        /// <param name="OrderSalesExWarehouseId">单据Id</param>
        /// <param name="WarehouseId">仓库Id</param>
        /// <returns></returns>
        [HttpGet("GetItem")]
        public async Task<IActionResult> GetItem([FromQuery] string WarehouseId ,[FromQuery] string OrderSalesExWarehouseId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetItem(WarehouseId,OrderSalesExWarehouseId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("销售出库-获取商品数据", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 新增销售出库单
        /// </summary>
        /// <param name="model">规格模型</param>
        /// <param name="OrderSalesExWarehouseItemString">商品子项字符串</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] OrderSalesExWarehouse model, [FromForm] string OrderSalesExWarehouseItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderSalesExWarehouseItem> list = new List<OrderSalesExWarehouseItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderSalesExWarehouseItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderSalesExWarehouseItem>>(OrderSalesExWarehouseItemString);
                    list.ForEach(x => {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        //主表Id由于是自增，由内部方法自动赋值,无需手动介入
                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;

                var isSuccess = await Services.AddOrderSalesExWareHouse(model, list);
                if (isSuccess)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("销售出库单-新增", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 修改销售出库单
        /// </summary>
        /// <param name="model">规格模型</param>
        /// <param name="OrderSalesExWarehouseItemString">商品子项字符串</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] OrderSalesExWarehouse model, [FromForm] string OrderSalesExWarehouseItemString)
        {
            var status = BaseStatus.CreateInstance();
            List<OrderSalesExWarehouseItem> list = new List<OrderSalesExWarehouseItem>();
            try
            {
                if (!string.IsNullOrEmpty(OrderSalesExWarehouseItemString))
                {
                    list = JsonConvert.DeserializeObject<List<OrderSalesExWarehouseItem>>(OrderSalesExWarehouseItemString);
                    list.ForEach(x => {
                        x.UpdateTime = StringHelper.GetTimeNow();
                        x.Updater = User.Identity.Name;

                        x.OrderSalesExWarehouseId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;
                var isSuccess = await Services.UpdateOrderSalesExWareHuse(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("销售出库单-修改", ex, HttpContext);
            }

            return Ok(status);
        }

        /// <summary>
        /// 批量删除销售出库单
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {

            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteOrderSalesExWareHuse(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("销售出库单-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 删除销售出库单
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]

        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteOrderSalesExWareHuse(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("销售出库单-删除", ex, HttpContext);
            }

            return Ok(status);
        }


        /// <summary>
        /// 修改单据状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpPut("UpdatStatus")]
        public async Task<IActionResult> UpdatStatus([FromForm] long Id, [FromForm] int Status)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                // 根据报价单 Id 查询数据库，找到对应的报价单对象
                var isSuccess = await Services.UpdatStatus(Id, Status);


                if (isSuccess)
                {
                    var msg = Status == 0 ? "反审成功" : "审核成功";
                    status.Code = 0;
                    status.Msg = msg;
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("销售出库单-修改状态", ex, HttpContext);
            }

            return Ok(status);
        }
    }
}
